import React, { useEffect, useCallback, useRef, useState } from 'react';
import { Tabs } from 'antd';
import { useHistory } from 'umi';
import styles from './index.less';
import PropTypes from 'prop-types';
import Filter from '../TablePage/components/filter2';

const { TabPane } = Tabs;

function WrapTabs(props) {
  const [activeKey, setActiveKey] = useState('');
  const keepAliveArr = useRef([]);
  const history = useHistory();

  const { location, route } = props;
  const { pathname, search } = location;
  const { routes } = route;

  // 获取全路径
  const getFullPathname = useCallback((pathname) => {
    let searchTemp = '';
    keepAliveArr.current.map((item) => {
      if (item.path === pathname) {
        searchTemp = item.search;
      }
      return null;
    });
    return pathname + searchTemp;
  }, []);

  useEffect(() => {
    // 空首页不处理
    if (pathname === '/') {
      return;
    }
    const find = keepAliveArr.current.find((item) => item.path === pathname);
    if (find) {
      // 如果已存在，需要判断query是否已更新
      const exitItem = keepAliveArr.current.find(
        (item) => item.path === pathname && search !== item.search,
      );
      /*
       * 注：在查看页面 path 相同，会认为是同一个页面
       * */
      if (exitItem) {
        const routeTemp = routes.find((item) => item.path === pathname);
        const View = routeTemp.component;
        exitItem.component = (
          <View
            {...props}
            key={getFullPathname(keepAliveArr.current, pathname + search)}
          />
        );
        exitItem.search = search;
      }
      setActiveKey(pathname);
      return;
    }
    const routeTemp = routes.find((item) => item.path === pathname);
    // 避免乱输入url报错
    if (!routeTemp) {
      return;
    }
    const View = routeTemp.component;

    keepAliveArr.current.push({
      ocmponent: View ? <View {...props} /> : null, // 克隆子组件
      name: routeTemp.name || '', // 设置标签名字
      path: pathname, // 设置路径，并以此为key
      search, // 查询条件，详情页，编辑页等带参数查询等页面需要用到
    });
    // 设置不超过10个标签页
    if (keepAliveArr.current.length > 10) {
      keepAliveArr.current.shift();
    }
    setActiveKey(pathname);
  }, [pathname]);

  // 切换标签
  const onChange = useCallback((key) => {
    history.push(getFullPathname(key));
  }, []);
  // 删除标签
  const onEdit = useCallback(
    (targetKey, action) => {
      if (action === 'remove') {
        keepAliveArr.current = keepAliveArr.current.filter(
          (item) => item.path !== targetKey,
        );
        // 1在当前页面删除，2在其他页面删除
        history.push(
          targetKey === pathname
            ? getFullPathname(
                keepAliveArr.current[keepAliveArr.current.length - 1].path,
              )
            : getFullPathname(pathname),
        );
      }
    },
    [pathname],
  );
  const tabBarRender = useCallback(
    (pros, DefaultTabBar) => {
      const offset = props.collapsed ? 80 : 208;
      const style = {
        position: 'fixed',
        width: `calc(100% - ${offset}px)`,
        left: offset,
        top: 46,
        zIndex: 100,
        transition: 'all 0.2s',
        boxShadow: '0px 1px 4px 0px rgba(0,21,41,0.12)',
        background: 'rgb(250, 250, 250)',
      };

      if (props.layout === 'topmenu') {
        style.left = 0;
        style.width = '100%';
      }

      return (
        <div style={style}>
          <DefaultTabBar {...pros} />
        </div>
      );
    },
    [props.collapsed, props.layout],
  );
  return (
    <div className={styles.pageTab}>
      <Tabs
        hideAdd
        type="editable-card"
        onChange={onChange}
        onEdit={onEdit}
        activeKey={activeKey}
        renderTabBar={tabBarRender}
      >
        {keepAliveArr.current.map((pane) => (
          <TabPane
            tab={pane.name}
            key={pane.path}
            closable={keepAliveArr.current.length !== 1}
          >
            <div style={{ margin: '62px 24px 0' }}>{pane.component}</div>
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
}
WrapTabs.propTypes = {
  location: PropTypes.object,
  route: PropTypes.array,
  collapsed: PropTypes.bool,
  layout: PropTypes.string,
};
export default React.memo(WrapTabs);
